<?php
class ManageStaticPagesController extends Controller {

	//public $backend_left_menu = "_left_menu";
	//public $backend_left_menu = "application.modules.static_pages.views.admin_menu._left_menu";
	//public $backend_left_menu_datas = array('list'	=>	array());
	//public $backend_left_menu_datas = false;
	public $pageTitle = "Manage Static Pages";
	private $_model;
	public $layout='//layouts/main';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to access 'index' and 'view' actions.
				'actions'=>array(''),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated users to access all actions
				'users'=>array('@'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	public function actionView($id) {
		Yii::app()->theme = 'backend';
		$this->render('view', array(
			'model' => $this->loadModel($id, 'StaticPage'),
		));
	}

	public function actionCreate() {
		$this->pageTitle = "Create Static Page";
		Yii::app()->theme = 'backend';
		$model = new StaticPage;

		//$this->performAjaxValidation($model, 'static-page-form');

		if (isset($_POST['StaticPage'])) {
			$model->setAttributes($_POST['StaticPage']);
			$fileUpload = CUploadedFile::getInstance($model, 'image');
			if (isset($fileUpload)) {
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url']; 
					if (!is_dir($uploadPath))
						mkdir($uploadPath,0777,true);
					
					$filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
					$fileUpload->saveAs($uploadPath . $filename);
					//CVarDumper::dump($uploadPath . $filename, 3, true);	exit;

					//Create lager and thumbnail image
					Yii::import('ext.phpthumb.EasyPhpThumb');
					$lagersPath = $thumbsPath = $uploadPath;

					// lager image
					$lagers = new EasyPhpThumb();
					$lagers->init();
					$lagers->setThumbsDirectory($lagersPath);
					$lagers->load($uploadPath . $filename)
							->resize(Yii::app()->controller->module->image['lager']['width'], 
											 Yii::app()->controller->module->image['lager']['height']
											)
							->save('lager_'.$filename);
					
					// thumbnails image
					$thumbs = new EasyPhpThumb();
					$thumbs->setThumbsDirectory($thumbsPath);
					$thumbs->load($uploadPath . $filename)
							->resize(Yii::app()->controller->module->image['thumbnail']['width'], 
											 Yii::app()->controller->module->image['thumbnail']['height']
											)
							->save('thumb_'.$filename);
					
					$model->image = $filename;
			}
			if ($model->save()) {
				if (Yii::app()->getRequest()->getIsAjaxRequest())
					Yii::app()->end();
				else
					$this->redirect(array('view', 'id' => $model->id));
			}
		} else {
			$model->is_published = 1;
		}

		$this->render('create', array( 'model' => $model));
	}

	public function actionUpdate($id) {
		Yii::app()->theme = 'backend';
		$model = $this->loadModel($id, 'StaticPage');

		//$this->performAjaxValidation($model, 'static-page-form');

		if (isset($_POST['StaticPage'])) {
			$model->setAttributes($_POST['StaticPage']);
			$fileUpload = CUploadedFile::getInstance($model, 'image');
			if (isset($fileUpload)) {
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url']; 
										
					if (!is_dir($uploadPath))
						mkdir($uploadPath,0777,true);
					
					// Delete old image
					if ($model->image) {
						if(is_file($uploadPath . '/' . $model->image)){
							unlink($uploadPath . '/' . $model->image);
						}
						if(is_file($uploadPath . '/lager_' . $model->image)){
							unlink($uploadPath . '/lager_' . $model->image);
						}
						if(is_file($uploadPath . '/thumb_' . $model->image)){
							unlink($uploadPath . '/thumb_' . $model->image);
						}
					}
					
					$filename = $model->alias . '.' . $fileUpload->getExtensionName(); //time() . mt_rand(0, 0xfff) . '.' . $fileUpload->getExtensionName();
					$fileUpload->saveAs($uploadPath . $filename);
					
					//Create lager and thumbnail image
					Yii::import('ext.phpthumb.EasyPhpThumb');
					$lagersPath = $thumbsPath = $uploadPath;
					
					// lager image
					$lagers = new EasyPhpThumb();
					$lagers->init();
					$lagers->setThumbsDirectory($lagersPath);
					$lagers->load($uploadPath . $filename)
							->resize(Yii::app()->controller->module->image['lager']['width'], 
											 Yii::app()->controller->module->image['lager']['height']
											)
							->save('lager_'.$filename);
					
					// thumbnails image
					$thumbs = new EasyPhpThumb();
					$thumbs->setThumbsDirectory($thumbsPath);
					$thumbs->load($uploadPath . $filename)
							->resize(Yii::app()->controller->module->image['thumbnail']['width'], 
											 Yii::app()->controller->module->image['thumbnail']['height']
											)
							->save('thumb_'.$filename);
					
					$model->image = $filename;
			}
			if ($model->save()) {
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
				));
	}

	public function actionDelete($id) {
		if (Yii::app()->getRequest()->getIsPostRequest()) {
			//$this->loadModel($id, 'StaticPage')->delete();
			$model = $this->loadModel($id);
			
			// X�a khoi db
			if ($model->delete() == 'ALL') 
			{
				// X�a image
				$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url'];
				$filename = $uploadPath . $model->image;
				if (is_file($filename)) @unlink($filename);
				$filenameThumb = $uploadPath . 'thumb_' . $model->image;
				if (is_file($filenameThumb)) @unlink($filenameThumb);
				$filenameLager = $uploadPath . 'lager_' . $model->image;
				if (is_file($filenameLager)) @unlink($filenameLager);
			}
			
			if (!Yii::app()->getRequest()->getIsAjaxRequest())
				$this->redirect(array('admin'));
		} else
			throw new CHttpException(400, Yii::t('app', 'Your request is invalid.'));
	}

	public function actionIndex() {
		Yii::app()->theme = 'backend';
		$dataProvider = new CActiveDataProvider('StaticPage');
		$this->render('index', array(
			'dataProvider' => $dataProvider,
		));
	}

	public function actionAdmin() {
		Yii::app()->theme = 'backend';
		if (isset($_POST['static-pages-grid_c0'])) {
			foreach ($_POST['static-pages-grid_c0'] as $ID)
			{
				$model = $this->loadModelByID($ID);

				// Xoa khoi db
				if ($model->delete() == 'ALL')
				{
					// X�a image
					$uploadPath = YiiBase::getPathOfAlias('webroot') . Yii::app()->controller->module->image['url'];
					$filename = $uploadPath . $model->image;
					if (is_file($filename)) @unlink($filename);
					$filenameThumb = $uploadPath . 'thumb_' . $model->image;
					if (is_file($filenameThumb)) @unlink($filenameThumb);
					$filenameLager = $uploadPath . 'lager_' . $model->image;
					if (is_file($filenameLager)) @unlink($filenameLager);
				}
			}
		}
		$model = new StaticPage('search');
		$model->unsetAttributes();
		if (isset($_GET['StaticPage'])) {
			$model->setAttributes($_GET['StaticPage']);
		}
		$this->render('admin', array(
			'model' => $model,
		));
	}
	
	protected function performAjaxValidation($models)
	{
			if(isset($_POST['ajax']) && $_POST['ajax']==='static-page-form')
			{
					echo CActiveForm::validate($models);
					Yii::app()->end();
			}
	}
	
	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 */
	public function loadModel()
	{
		if($this->_model===null)
		{
			if(isset($_GET['id']))
				$this->_model=StaticPage::model()->findbyPk($_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
	
	public function loadModelByID($id)
	{
			$model = StaticPage::model()->findByPk($id);
			if ($model === null)
					throw new CHttpException(404, 'The requested page does not exist.');
			return $model;
	}
	

	public function actionUpload(){
		Yii::import('ext.ckeditor.CkEditorUploader');
		$config = array(
				'url'=>$this->module->image['url'],
		);
		CkEditorUploader::$config = $config;
		CkEditorUploader::upload();
	}
}